package com.ytjj.qmyx.mall.service.impl;

import com.ytjj.common.constants.CopyWriterConstant;
import com.ytjj.common.constants.SysConfigConstants;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.CopyWriterConfigUtil;
import com.ytjj.common.utils.OrderUtils;
import com.ytjj.common.utils.SysConfigUtil;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.qmyx.mall.mapper.OrdersSpecMapper;
import com.ytjj.qmyx.mall.model.Orders;
import com.ytjj.qmyx.mall.model.OrdersInfo;
import com.ytjj.qmyx.mall.model.ProductSpec;
import com.ytjj.qmyx.mall.model.request.H5CartCreateOrderRequest;
import com.ytjj.qmyx.mall.model.request.H5CartItemRequest;
import com.ytjj.qmyx.mall.model.response.ProductResponse;
import com.ytjj.qmyx.mall.model.response.ProductSpecResponse;
import com.ytjj.qmyx.mall.service.CreateOrderService;
import com.ytjj.qmyx.mall.service.OrdersService;
import com.ytjj.qmyx.mall.service.ProductService;
import com.ytjj.qmyx.users.client.UsersClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
/**
 * H5购物车创建订单的方式
 */
@Slf4j
@Service("H5CART")
public class H5OrdersCartServiceImpl implements CreateOrderService<H5CartCreateOrderRequest>  {

    @Autowired
    private UsersClient usersClient;

    @Autowired
    private RedisService redisService;

    @Autowired
    private ProductService productService;

    @Autowired
    private OrdersService ordersService;

    @Resource
    private SysConfigUtil sysConfigUtil;

    @Resource
    private CopyWriterConfigUtil copyWriterConfigUtil;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private OrdersSpecMapper ordersSpecMapper;

    @Override
    @Transactional
    public Integer createOrder(H5CartCreateOrderRequest request) {
        return 0;
    }

    @Override
    @Transactional
    public Integer cartCreateOrder(H5CartCreateOrderRequest request) {
        Integer orderId=null;
        // 购物车创建订单
        Integer userId = null;
        if(StringUtils.isNotEmpty(request.getTel())){
            // 获取用户id 用户服务处理
            userId = usersClient.h5GetUserIdByTel(request.getTel(), request.getChannel(), TokenUtil.getToken());
        }
        String orderParentNo = OrderUtils.getOrderCode(userId);//组合订单号
        BigDecimal realTotalMoney = new BigDecimal(0);
        BigDecimal goodsMoney = new BigDecimal(0);
        for (H5CartItemRequest cartItem : request.getCartItemList()) {

            //冻结库存前查一下库存是否足够用
            log.info("=============冻结库存前查一下库存是否足够用5=====================参数{},{}",cartItem.getProductId(), cartItem.getProductSpecId());
            boolean b = ordersService.checkProductStock(cartItem.getProductId(), cartItem.getProductSpecId(),cartItem.getProductSum());
            if (!b){
                throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.INSUFFICIENT_STOCK));
            }

            ProductSpecResponse productSpec = productService.getProductSpecInfoById(cartItem.getProductSpecId());
//            if (Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.IS_STOCE_VERIFY)) > 0 && productSpec.getStock() <= 0) {
//                throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.INSUFFICIENT_STOCK));
//            }
            goodsMoney = goodsMoney.add(productSpec.getOriginalPrice());
            realTotalMoney = realTotalMoney.add(productSpec.getPrice());
        }
        //主订单
        Orders orders = ordersService.saveOrders(userId, request.getTel(),request.getProvince(),request.getCity(),request.getArea(), request.getAddress(), request.getUserName(),
                goodsMoney.setScale(2, BigDecimal.ROUND_UP),
                realTotalMoney.setScale(2, BigDecimal.ROUND_UP),request.getOrderSource(),request.getChannel(),TokenUtil.getToken(),orderParentNo,request.getDomainUrl(),null,null);

        for (H5CartItemRequest cartItem : request.getCartItemList()) {
            ProductResponse product = productService.getProductById(cartItem.getProductId(),request.getPageSourceV2());
            ProductSpecResponse productSpec = productService.getProductSpecInfoById(cartItem.getProductSpecId());
//            if (Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.IS_STOCE_VERIFY)) > 0 && productSpec.getStock() <= 0) {
//                throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.INSUFFICIENT_STOCK));
//            }
            // 订单明细
            OrdersInfo ordersInfo = ordersService.saveOrdersInfo(orders.getId(), product.getId(), product.getProductName(), product.getProductImg(),
                    productSpec.getPrice().multiply(new BigDecimal(cartItem.getProductSum())), productSpec.getOriginalPrice().multiply(new BigDecimal(cartItem.getProductSum())), product.getWarehouse(), product.getWarehouseName(),
                    product.getWarehouseRule(), cartItem.getProductSpecId(), productSpec.getSkuSpec(), product.getBankerId(),
                    productSpec.getId(), null, null, null, null,product.getDescr(),
                    0,request.getPageSourceV2(),null,1,0, productSpec.getCostPrice().multiply(new BigDecimal(cartItem.getProductSum())),cartItem.getProductSum());
            try {
                // 记录订单规格信息
                ProductSpec productSpecs = ordersSpecMapper.selectOrderSpec(cartItem.getProductSpecId());
                ordersSpecMapper.insertOrderSpec(productSpecs.getSkuSpec(),orders.getId(),productSpecs.getPrice(),productSpecs.getOriginalPrice(),productSpecs.getCostPrice());
            }catch (Exception e){
                log.error("发送到rabbitmq错误",e);
            }
            orderId = orders.getId();
        }
        return orderId;
    }
}
